//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.ccp.dev.core.basic.util;

import com.ccp.dev.core.basic.api.ISysDataSource;
import com.ccp.dev.core.basic.api.ISysDataSourceService;
import com.ccp.dev.core.basic.db.datasource.DbContextHolder;
import com.ccp.dev.core.basic.mybatis.Dialect;
import com.ccp.dev.core.basic.mybatis.dialect.*;
import com.ccp.dev.core.util.AppUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class DialectUtil {
    public DialectUtil() {
    }

    public static Dialect getDialect(String dbType) throws Exception {
        Object dialect;
        if (dbType.equals("oracle")) {
            dialect = new OracleDialect();
        } else if (dbType.equals("mssql")) {
            dialect = new SQLServer2005Dialect();
        } else if (dbType.equals("db2")) {
            dialect = new DB2Dialect();
        } else if (dbType.equals("mysql")) {
            dialect = new MySQLDialect();
        } else if (dbType.equals("h2")) {
            dialect = new H2Dialect();
        } else if (dbType.equals("postgresql")) {
            dialect = new PostgreSQLDialect();
        } else {
            if (!dbType.equals("dm")) {
                throw new Exception("没有设置合适的数据库类型");
            }
            dialect = new DmDialect();
        }

        return (Dialect) dialect;
    }

    public static Dialect getCurrentDialect() throws Exception {
        return getDialect(DbContextHolder.getDbType());
    }

    public static Dialect getDialect(ISysDataSource sysDataSource) throws Exception {
        return getDialect(sysDataSource.getDbType());
    }

    @Value("${mybatis.configuration.database-id}")
    private String dbType;

    public Dialect getDialectByDataSourceAlias(String alias) throws Exception {
        ISysDataSourceService sysDataSourceService = AppUtil.getBean(ISysDataSourceService.class);
        ISysDataSource sysDataSource = sysDataSourceService.getByAlias(alias);
        return sysDataSource == null ? getDialect(dbType) : getDialect(sysDataSource);
    }
}
